<template>
  <div class="app-container">
    <!-- 查询条件 -->
    <el-card class="search-card">
      <el-form :model="queryParams">
        <!-- 第一行 -->
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="日期范围">
              <el-date-picker v-model="dateRange" type="datetimerange" range-separator="至" start-placeholder="开始日期"
                end-placeholder="结束日期" value-format="YYYY-MM-DD HH:mm:ss" style="width: 100%;"
                @change="handleDateChange" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="报警类型">
              <el-select v-model="queryParams.alarmType" placeholder="全部类型" clearable style="width: 100%;">
                <el-option label="设备报警" value="设备报警" />
                <el-option label="水质报警" value="水质报警" />
                <el-option label="系统报警" value="系统报警" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="报警等级">
              <el-select v-model="queryParams.alarmLevel" placeholder="全部等级" clearable style="width: 100%;">
                <el-option label="危急" value="危急" />
                <el-option label="重要" value="重要" />
                <el-option label="普通" value="普通" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第二行 -->
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="处理状态">
              <el-select v-model="queryParams.status" placeholder="全部状态" clearable style="width: 100%;">
                <el-option label="未处理" value="未处理" />
                <el-option label="处理中" value="处理中" />
                <el-option label="已解决" value="已解决" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item>
              <el-button type="primary" @click="handleQuery">查询</el-button>
              <el-button @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 搜索框 -->
        <el-input v-model="queryParams.searchText" placeholder="搜索报警内容" clearable
          style="width: 300px; margin-right: 10px;" @keyup.enter="handleQuery">
          <template #append>
            <el-button :icon="Search" @click="handleQuery" />
          </template>
        </el-input>
      </el-form>
    </el-card>

    <el-row :gutter="20" class="mt-20">
      <!-- 报警列表 -->
      <el-col :span="16">
        <el-card>
          <template #header>
            <div class="table-header">
              <span>报警信息列表</span>
              <el-tag type="info">共 {{ total }} 条记录</el-tag>
            </div>
          </template>
          <el-table :data="alarmList" style="width: 100%" v-loading="loading">
            <el-table-column prop="alarmTime" label="报警时间" width="150" />
            <el-table-column prop="alarmType" label="报警类型" width="100">
              <template #default="{ row }">
                <el-tag :type="getAlarmTypeTag(row.alarmType)">{{ row.alarmType }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="alarmLevel" label="报警等级" width="100">
              <template #default="{ row }">
                <el-tag :type="getLevelTag(row.alarmLevel)">{{ row.alarmLevel }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="location" label="报警位置" width="120" />
            <el-table-column prop="description" label="报警描述" show-overflow-tooltip />
            <el-table-column prop="status" label="处理状态" width="100">
              <template #default="{ row }">
                <el-tag :type="getStatusTag(row.status)">{{ row.status }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="handler" label="处理人员" width="120" />
            <el-table-column label="操作" width="120" fixed="right">
              <template #default="{ row }">
                <el-button v-if="row.status === '未处理'" type="primary" size="small" @click="handleProcess(row)">
                  处理
                </el-button>
                <el-button v-else type="info" size="small" @click="handleDetail(row)">
                  详情
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="pagination">
            <el-pagination v-model:current-page="queryParams.pageNum" v-model:page-size="queryParams.pageSize"
              :total="total" layout="total, sizes, prev, pager, next, jumper" :page-sizes="[10, 20, 50, 100]"
              @size-change="handleQuery" @current-change="handleQuery" />
          </div>
          <el-row :gutter="24" class="mt-20">
            <!-- 报警趋势分析 -->
            <el-col :span="12">
              <ECharts :option="trendOption" />
            </el-col>
            <!-- 报警类型占比 -->
            <el-col :span="12">
              <ECharts :option="typeOption" />
            </el-col>
          </el-row>
          <el-row :gutter="24" class="mt-20">
            <!-- 报警趋势分析 -->
            <el-col :span="12">
              <ECharts :option="efficiencyOptions" />
            </el-col>
            <!-- 报警类型占比 -->
            <el-col :span="12">
              <ECharts :option="highIncidenceOptions" />
            </el-col>
          </el-row>
        </el-card>
      </el-col>

      <!-- 实时报警和统计 -->
      <el-col :span="8">
        <el-card class="mb-20">
          <template #header>
            <span>实时报警</span>
            <el-tag type="danger" style="float: right">
              {{ realtimeAlarms.length }} 条未处理
            </el-tag>
          </template>
          <el-scrollbar height="300px">
            <div v-for="alarm in realtimeAlarms" :key="alarm.id" class="realtime-alarm-item"
              :class="'level-' + alarm.alarmLevel">

              <div class="alarm-location">{{ alarm.location }}</div>
              <div class="alarm-description">{{ alarm.description }}</div>
              <div class="alarm-type">
                <div class="alarm-time">{{ alarm.alarmTime }}</div>
                <div>
                  {{ alarm.alarmType }}
                </div>
              </div>
            </div>
          </el-scrollbar>
        </el-card>

        <el-card>
          <template #header>
            <span>报警统计</span>
          </template>
          <div class="stat-cards">
            <div class="stat-card danger">
              <div class="stat-value">{{ stats.critical }}</div>
              <div class="stat-label">今日危急</div>
            </div>
            <div class="stat-card warning">
              <div class="stat-value">{{ stats.important }}</div>
              <div class="stat-label">今日重要</div>
            </div>
            <div class="stat-card normal">
              <div class="stat-value">{{ stats.normal }}</div>
              <div class="stat-label">今日普通</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>



    <!-- 报警详情对话框 -->
    <el-dialog v-model="detailDialogVisible" :title="'报警详情 - ' + currentAlarm?.id" width="60%">
      <div v-if="currentAlarm" class="alarm-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="报警编号">{{ currentAlarm.id }}</el-descriptions-item>
          <el-descriptions-item label="报警时间">{{ currentAlarm.alarmTime }}</el-descriptions-item>
          <el-descriptions-item label="报警类型">
            <el-tag :type="getAlarmTypeTag(currentAlarm.alarmType)">{{ currentAlarm.alarmType }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="报警等级">
            <el-tag :type="getLevelTag(currentAlarm.alarmLevel)">{{ currentAlarm.alarmLevel }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="报警位置">{{ currentAlarm.location }}</el-descriptions-item>
          <el-descriptions-item label="处理状态">
            <el-tag :type="getStatusTag(currentAlarm.status)">{{ currentAlarm.status }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="处理人员">{{ currentAlarm.handler || '无' }}</el-descriptions-item>
          <el-descriptions-item label="处理时间">{{ currentAlarm.handleTime || '无' }}</el-descriptions-item>
          <el-descriptions-item label="报警描述" :span="2">
            <div class="description-content">
              {{ getFullDescription(currentAlarm) }}
            </div>
          </el-descriptions-item>
          <el-descriptions-item label="处理记录" :span="2" v-if="currentAlarm.status !== '未处理'">
            <el-timeline>
              <el-timeline-item v-for="(record, index) in processRecords" :key="index" :timestamp="record.time"
                :type="record.type" :color="record.color">
                <div class="record-content">
                  <strong>{{ record.action }}</strong> - {{ record.operator }}
                  <p v-if="record.remark" class="remark">{{ record.remark }}</p>
                </div>
              </el-timeline-item>
            </el-timeline>
          </el-descriptions-item>
        </el-descriptions>
      </div>
      <template #footer>
        <el-button @click="detailDialogVisible = false">关闭</el-button>
        <el-button type="primary" @click="handleProcess(currentAlarm)"
          v-if="currentAlarm?.status === '未处理' || currentAlarm?.status === '处理中'">
          {{ currentAlarm?.status === '处理中' ? '继续处理' : '处理' }}
        </el-button>
      </template>
    </el-dialog>

    <!-- 处理报警对话框 -->
    <el-dialog v-model="processDialogVisible" :title="'处理报警 - ' + currentAlarm?.id" width="50%">
      <div v-if="currentAlarm" class="process-form">
        <el-form :model="processForm" label-width="100px" :rules="rules" ref="processFormRef">
          <el-form-item label="报警编号">
            <el-input v-model="currentAlarm.id" disabled />
          </el-form-item>
          <el-form-item label="报警类型">
            <el-input v-model="currentAlarm.alarmType" disabled />
          </el-form-item>
          <el-form-item label="报警位置">
            <el-input v-model="currentAlarm.location" disabled />
          </el-form-item>
          <el-form-item label="处理状态" prop="status">
            <el-select v-model="processForm.status" placeholder="请选择处理状态">
              <el-option v-if="currentAlarm.status === '未处理'" label="处理中" value="处理中" />
              <el-option label="已解决" value="已解决" />
            </el-select>
          </el-form-item>
          <el-form-item label="处理说明" prop="description">
            <el-input v-model="processForm.description" type="textarea" :rows="4" placeholder="请输入处理说明" />
          </el-form-item>
          <el-form-item label="上传附件">
            <el-upload action="#" list-type="picture-card" :auto-upload="false" :limit="3" :on-change="handleFileChange"
              :file-list="processForm.files">
              <el-icon>
                <Plus />
              </el-icon>
            </el-upload>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <el-button @click="processDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitProcess">确认处理</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { Search, Plus } from '@element-plus/icons-vue'
import ECharts from '@/components/ECharts'
import { ElMessage } from 'element-plus'

// 查询参数
const queryParams = ref({
  startDate: '',
  endDate: '',
  alarmType: '',
  alarmLevel: '',
  status: '',
  searchText: '',
  pageNum: 1,
  pageSize: 10
})

// 报警列表数据
const alarmList = ref([{
  id: 'WO-2023-001',
  alarmTime: '2023-06-15 08:23:45',
  alarmType: '设备报警',
  alarmLevel: '危急',
  location: '1号水泵房',
  description: '1号水泵电机温度过高',
  status: '未处理',
  handler: '',
  handleTime: ''
},
{
  id: 'WO-2023-002',
  alarmTime: '2023-06-15 09:12:33',
  alarmType: '水质报警',
  alarmLevel: '重要',
  location: '2号沉淀池',
  description: '水质浊度超标',
  status: '处理中',
  handler: '张工程师',
  handleTime: '2023-06-15 09:30:00'
},
{
  id: 'WO-2023-003',
  alarmTime: '2023-06-15 10:05:18',
  alarmType: '系统报警',
  alarmLevel: '普通',
  location: '中央控制系统',
  description: '数据采集异常',
  status: '已解决',
  handler: '李技术员',
  handleTime: '2023-06-15 11:20:45'
},
{
  id: 'WO-2023-004',
  alarmTime: '2023-06-15 11:37:22',
  alarmType: '设备报警',
  alarmLevel: '危急',
  location: '3号加药间',
  description: '加药泵运行异常',
  status: '未处理',
  handler: '',
  handleTime: ''
},
{
  id: 'WO-2023-005',
  alarmTime: '2023-06-15 12:15:09',
  alarmType: '水质报警',
  alarmLevel: '重要',
  location: '出厂水监测点',
  description: '余氯含量不足',
  status: '处理中',
  handler: '王化验员',
  handleTime: '2023-06-15 12:30:00'
},
{
  id: 'WO-2023-006',
  alarmTime: '2023-06-15 13:42:56',
  alarmType: '设备报警',
  alarmLevel: '普通',
  location: '4号清水池',
  description: '水位传感器故障',
  status: '未处理',
  handler: '',
  handleTime: ''
},
{
  id: 'WO-2023-007',
  alarmTime: '2023-06-15 14:28:34',
  alarmType: '系统报警',
  alarmLevel: '重要',
  location: '数据服务器',
  description: '存储空间不足',
  status: '已解决',
  handler: '赵管理员',
  handleTime: '2023-06-15 15:45:12'
},
{
  id: 'WO-2023-008',
  alarmTime: '2023-06-15 16:13:47',
  alarmType: '水质报警',
  alarmLevel: '危急',
  location: '1号滤池',
  description: '滤后水浊度高',
  status: '处理中',
  handler: '张工程师',
  handleTime: '2023-06-15 16:30:00'
},
{
  id: 'WO-2023-009',
  alarmTime: '2023-06-15 17:25:19',
  alarmType: '设备报警',
  alarmLevel: '普通',
  location: '2号水泵房',
  description: '水泵振动异常',
  status: '未处理',
  handler: '',
  handleTime: ''
},
{
  id: 'WO-2023-010',
  alarmTime: '2023-06-15 18:39:02',
  alarmType: '系统报警',
  alarmLevel: '重要',
  location: '监控中心',
  description: '视频监控异常',
  status: '已解决',
  handler: '李技术员',
  handleTime: '2023-06-15 19:15:33'
}])
const total = ref(0)
const loading = ref(false)

// 实时报警数据
const realtimeAlarms = computed(() => {
  return alarmList.value.filter(alarm => alarm.status === '未处理')
})

// 统计信息
const stats = ref({
  critical: 0,
  important: 0,
  normal: 0
})

// 对话框状态
const detailDialogVisible = ref(false)
const processDialogVisible = ref(false)

// 当前操作的报警
const currentAlarm = ref(null)

// 处理表单
const processForm = ref({
  status: '',
  description: '',
  files: []
})

// 表单验证规则
const rules = {
  status: [{ required: true, message: '请选择处理状态', trigger: 'change' }],
  description: [{ required: true, message: '请输入处理说明', trigger: 'blur' }]
}

// 处理记录数据
const processRecords = ref([
  {
    time: '2023-06-15 08:23:45',
    action: '报警触发',
    operator: '系统',
    remark: '',
    type: 'primary',
    color: '#409EFF'
  },
  {
    time: '2023-06-15 08:30:12',
    action: '分配处理人员',
    operator: '调度中心',
    remark: '分配给张工程师处理',
    type: 'success',
    color: '#67C23A'
  },
  {
    time: '2023-06-15 09:15:33',
    action: '现场检查',
    operator: '张工程师',
    remark: '确认电机温度传感器故障',
    type: 'warning',
    color: '#E6A23C'
  }
])

// 图表配置
const trendOption = ref({
  title: {
    text: '报警趋势分析'
  },
  tooltip: {
    trigger: 'axis'
  },
  xAxis: {
    type: 'category',
    boundaryGap: false,
    data: ['00:00', '04:00', '08:00', '12:00', '16:00', '20:00']
  },
  yAxis: {
    type: 'value'
  },
  series: [
    {
      name: '报警次数',
      type: 'line',
      smooth: true,
      data: [5, 10, 12, 6, 9, 7]
    }
  ]
})

const typeOption = ref({
  title: {
    text: '报警类型占比',
    left: 'center'
  },
  tooltip: {
    trigger: 'item'
  },
  legend: {
    orient: 'vertical',
    left: 'left'
  },
  series: [
    {
      name: '报警类型',
      type: 'pie',
      radius: ['50%', '70%'],
      avoidLabelOverlap: false,
      label: {
        show: false,
        position: 'center'
      },
      emphasis: {
        label: {
          show: true,
          fontSize: '30',
          fontWeight: 'bold'
        }
      },
      itemStyle: {
        borderRadius: 10
      },
      data: [
        { value: 10, name: '设备报警', itemStyle: { color: '#f0ad4e' } },
        { value: 15, name: '水质报警', itemStyle: { color: '#5cb85c' } },
        { value: 5, name: '系统报警', itemStyle: { color: '#2f4b7c' } }
      ]
    }
  ]
})
const efficiencyOptions = ref({
  title: {
    text: '处理效率分析'
  },
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'shadow'
    }
  },
  xAxis: {
    type: 'category',
    data: ['危急', '重要', '普通']
  },
  yAxis: {
    type: 'value',
    name: '处理时间(分钟)'
  },
  series: [
    {
      name: '处理时间',
      type: 'bar',
      data: [100, 200, 350],
      itemStyle: {
        normal: {
          color: function(params) {
            const colors = ['#d9534f', '#f0ad4e', '#5cb85c'];
            return colors[params.dataIndex];
          }
        }
      }
    }
  ]
})
const highIncidenceOptions = ref({
  title: {
    text: '高发报警 TOP5'
  },
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'shadow'
    }
  },
  xAxis: {
    type: 'value'
  },
  yAxis: {
    type: 'category',
    data: ['孔异常', '气泄漏', '泵故障', '度异常', '温过高']
  },
  series: [
    {
      name: '报警次数',
      type: 'bar',
      data: [28, 20, 16, 10, 5],
      barWidth: '60%',
      itemStyle: {
        normal: {
          color: function(params) {
            const colors = ['#5bc0de', '#f0ad4e', '#5cb85c', '#d9534f', '#d9534f'];
            return colors[params.dataIndex];
          }
        }
      }
    }
  ]
})
// 获取完整的报警描述
const getFullDescription = (alarm) => {
  const descriptions = {
    'WO-2023-001': '1号水泵电机温度过高，超过安全阀值，需要立即检查冷却系统和电机状态。',
    'WO-2023-002': '2号沉淀池水质浊度超标，可能影响后续处理工艺，需检查沉淀效果和投药量。',
    'WO-2023-003': '中央控制系统数据采集异常，部分传感器数据丢失，需检查通讯线路和采集模块。',
    'WO-2023-004': '3号加药间加药泵运行异常，流量不稳定，需检查泵体和控制系统。',
    'WO-2023-005': '出厂水监测点余氯含量低于标准值，需调整加氯量并检查加氯设备。',
    'WO-2023-006': '4号清水池水位传感器故障，显示水位低于实际值，需校准或更换传感器。',
    'WO-2023-007': '数据服务器存储空间不足，剩余空间仅5%，需清理日志文件或扩容存储。',
    'WO-2023-008': '1号滤池滤后水浊度异常升高，可能滤料层出现问题，需检查反冲洗效果。',
    'WO-2023-009': '2号水泵房水泵振动异常，伴有异响，需检查轴承和联轴器对中情况。',
    'WO-2023-010': '监控中心视频监控信号丢失，多个摄像头无图像，需检查网络和电源。'
  }
  return descriptions[alarm.id] || alarm.description
}


// 查询处理
const handleQuery = () => {
  queryParams.value.pageNum = 1
  fetchAlarmList()
}

// 重置查询
const resetQuery = () => {
  queryParams.value = {
    startDate: '',
    endDate: '',
    alarmType: '',
    alarmLevel: '',
    status: '',
    searchText: '',
    pageNum: 1,
    pageSize: 10
  }
  fetchAlarmList()
}

// 查看详情
const handleDetail = (row) => {
  currentAlarm.value = row
  detailDialogVisible.value = true
}

// 处理报警
const handleProcess = (row) => {
  currentAlarm.value = row
  processForm.value = {
    status: row.status === '未处理' ? '处理中' : '已解决',
    description: '',
    files: []
  }

  // 如果是从详情对话框点击的处理按钮，先关闭详情对话框
  detailDialogVisible.value = false
  processDialogVisible.value = true
}

// 文件上传处理
const handleFileChange = (file, fileList) => {
  processForm.value.files = fileList
}

// 提交处理
const submitProcess = async () => {
  try {
    // 验证表单
    await processFormRef.value.validate()

  } catch (error) {
    console.error('处理报警失败:', error)
  }
}

// 获取标签类型
const getAlarmTypeTag = (type) => {
  const map = {
    '设备报警': 'danger',
    '水质报警': 'success',
    '系统报警': 'primary'
  }
  return map[type] || 'info'
}

const getLevelTag = (level) => {
  const map = {
    '危急': 'danger',
    '重要': 'warning',
    '普通': 'info'
  }
  return map[level] || ''
}

const getStatusTag = (status) => {
  const map = {
    '未处理': 'danger',
    '处理中': 'warning',
    '已解决': 'success'
  }
  return map[status] || 'info'
}

// 初始化
onMounted(() => {

  // 设置默认查询时间为今天
  const today = new Date()
  const startDate = new Date(today.setHours(0, 0, 0, 0))
  const endDate = new Date(today.setHours(23, 59, 59, 999))

  queryParams.value.startDate = startDate.toLocaleString()
  queryParams.value.endDate = endDate.toLocaleString()
})
</script>

<style scoped>
.alarm-management {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.mt-20 {
  margin-top: 20px;
}

.mb-20 {
  margin-bottom: 20px;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.realtime-alarm-item {
  padding: 12px;
  margin-bottom: 10px;
  border-radius: 4px;
  background-color: #f5f7fa;
  position: relative;
  padding-left: 60px;
}

.realtime-alarm-item::before {
  content: '';
  position: absolute;
  left: 0;
  top: 0;
  bottom: 0;
  width: 4px;
}

.realtime-alarm-item.level-危急::before {
  background-color: #f56c6c;
}

.realtime-alarm-item.level-重要::before {
  background-color: #e6a23c;
}

.realtime-alarm-item.level-普通::before {
  background-color: #909399;
}

.alarm-time {
  font-size: 12px;
  color: #999;
}

.alarm-location {
  font-weight: bold;
  margin-bottom: 5px;
}

.alarm-description {
  color: #666;
  font-size: 14px;
  margin-bottom: 5px;
}

.alarm-type {
  font-size: 12px;
  color: #409EFF;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.stat-cards {
  display: flex;
  justify-content: space-around;
  text-align: center;
}

.stat-card {
  padding: 15px;
  border-radius: 4px;
  width: 30%;
}

.stat-card.danger {
  background-color: #fef0f0;
  color: #f56c6c;
}

.stat-card.warning {
  background-color: #fdf6ec;
  color: #e6a23c;
}

.stat-card.normal {
  background-color: #f4f4f5;
  color: #909399;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 5px;
}

.stat-label {
  font-size: 14px;
}

.alarm-detail {
  padding: 10px;
}

.description-content {
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
  white-space: pre-line;
}

.record-content {
  padding: 5px 0;
}

.remark {
  margin-top: 5px;
  color: #666;
  font-size: 14px;
  padding-left: 10px;
  border-left: 2px solid #e6e6e6;
}

.process-form {
  padding: 0 20px;
}
</style>